"""
Copyright (c) 2022 Huawei Technologies Co.,Ltd.

openGauss is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:

          http://license.coscl.org.cn/MulanPSL2

THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
See the Mulan PSL v2 for more details.
"""
"""
Case Type   : 故障&可靠性测试
Case Name   : 套接字文件权限异常恢复，执行数据恢复
Create At   : 2020/07/27
@zou_jialiang0505328126
Description :
    1. 获取套接字文件路径
    2. 获取套接字文件名
    3. 执行gs_dump，导出postgres数据库全量信息
    4. 修改套接字文件权限为不可读不可写
    5. 连接数据库
    6. 运行tpcc指令
    7. 恢复socket文件权限
    8. 连接数据库
    9. 数据恢复
    10. 运行tpcc指令
Expect      :
    1. 返回套接字文件路径
    2. 返回套接字文件名
    3. 执行成功，返回信息
    4. 执行成功，无返回信息
    5. 非socket连接连接成功：
    6. 运行正常，返回信息中关注
    7. 执行成功，无返回信息
    8. 非socket连接连接成功
    9. 返回信息
    10. 返回信息关注
History     :
    modified: 2020/12/09  modified by @wan005,修改恢复数据库为新创建数据库，防止恢复失败导致后续用例失败
"""
import os
import unittest
from yat.test import Node
import time
from yat.test import macro
import sys

sys.path.append(sys.path[0] + "/../")
from testcase.utils.Logger import Logger
from testcase.utils.Constant import Constant
from testcase.utils.Common import Common
from testcase.utils.CommonSH import *

logger = Logger()
common = Common()



class StopImmediate(unittest.TestCase):
    dbPrimaryUserNode = Node(node='PrimaryDbUser')
    dbPrimaryRootNode = Node(node='PrimaryRoot')
    file_name = ''
    primary_sh = CommonSH('PrimaryDbUser')
    standby_1_sh = CommonSH('Standby1DbUser')
    standby_2_sh = CommonSH('Standby2DbUser')
    dump_file_name = 'test_pid.tar'
    nodes_tuple = ('PrimaryDbUser', 'Standby1DbUser', 'Standby2DbUser')


    @RestartDbCluster(*nodes_tuple)
    def setUp(self):
        logger.info("-----------this is setup-----------")
        logger.info('------------Opengauss_Reliability_Dbsys_Case168.py start------------')
        self.Constant = Constant()
        self.dbname = 'dbsys_case168_db'
        logger.info("---------------------create database--------------------")
        result = self.primary_sh.executDbSql(f'create database { self.dbname};')
        logger.info(result)
        self.assertIn(self.Constant.CREATE_DATABASE_SUCCESS_MSG, result)

    def test_stop_immediate(self):
        time.sleep(30)
        logger.info("----------------------get socket file path--------------")
        sql = "show unix_socket_directory"
        getfilepath_msg = self.primary_sh.executDbSql(sql)
        logger.info(getfilepath_msg)
        file_path = getfilepath_msg.split('\n')[2]
        logger.info(file_path)

        logger.info("----------------------get socket file name--------------")
        get_file_list_cmd = f'ls -a {file_path}'
        logger.info(get_file_list_cmd)
        file_list = self.dbPrimaryUserNode.sh(get_file_list_cmd).result()
        logger.info(file_list)
        socket_file_name = ''
        for file in file_list.split():
            logger.info(file)
            if (self.dbPrimaryUserNode.db_port not in file) or ('lock' in file):
                pass
            else:
                socket_file_name = file
        logger.info(socket_file_name)
        self.file_name = file_path + "/" + socket_file_name

        logger.info('--------------------dump file-------------------------')
        dump_msg = self.primary_sh.dumpFile(os.path.join(macro.DB_INSTANCE_PATH, self.dump_file_name))
        logger.info(dump_msg)
        flag = 'dump database ' + self.dbPrimaryUserNode.db_name + ' successfully'
        self.assertIn(flag, dump_msg)

        logger.info("------------------modify file permission----------------------")
        delete_cmd = f'chmod 000 {self.file_name}'
        self.dbPrimaryRootNode.sh(delete_cmd).result()
        logger.info(delete_cmd)

        logger.info("----------------------connect opengauss----------------------")
        no_socket_connect_msg = self.primary_sh.nosocketConnect()
        logger.info(no_socket_connect_msg)
        self.assertEqual(no_socket_connect_msg, '')

        socket_connect_msg = self.primary_sh.socket_connect(file_path)
        logger.info(socket_connect_msg)
        self.assertIn(self.Constant.FAILED_CONNECT_DB, socket_connect_msg)

        logger.info("---------------------start TPCC----------------------")
        tpcc_result = common.startTPCC(self.dbPrimaryRootNode, macro.TPCC_PATH)
        logger.info('-------------' + tpcc_result + '-----------------------')
        logger.info(tpcc_result)
        self.assertTrue(tpcc_result.find(self.Constant.TPCC_SUCCESS_MSG) > -1)

        logger.info("------------------------recover socket file------------------")
        recover_cmd = f'chmod 700 {self.file_name}'
        logger.info(recover_cmd)
        self.dbPrimaryRootNode.sh(recover_cmd)

        logger.info("----------------------connect opengauss----------------------")
        no_socket_connect_msg = self.primary_sh.nosocketConnect()
        logger.info(no_socket_connect_msg)
        self.assertEqual(no_socket_connect_msg, '')

        socket_connect_msg = self.primary_sh.socket_connect(file_path)
        logger.info(socket_connect_msg)
        logger.info(type(socket_connect_msg))
        self.assertEqual(socket_connect_msg, '')

        logger.info('--------------------recover file-------------------------')
        dump_msg = self.primary_sh.restoreFile(os.path.join(macro.DB_INSTANCE_PATH, self.dump_file_name), get_detail=True, dbname=self.dbname)
        logger.info(dump_msg)
        self.assertTrue(dump_msg.find(self.Constant.RESTORE_SUCCESS_MSG) > -1)

        logger.info("---------------------start TPCC----------------------")
        tpcc_result = common.startTPCC(self.dbPrimaryRootNode, macro.TPCC_PATH)
        logger.info('-------------' + tpcc_result + '-----------------------')
        logger.info(tpcc_result)
        self.assertTrue(tpcc_result.find(self.Constant.TPCC_SUCCESS_MSG) > -1)

        logger.info("------------------------recover socket file------------------")
        recover_cmd = f'chmod 700 {self.file_name}'
        logger.info(recover_cmd)
        self.dbPrimaryRootNode.sh(recover_cmd)

        # 校验刷脏页是否完成
        logger.info('校验刷脏页是否完成')
        dirty_page_finshed_flag = self.standby_1_sh.check_whether_remain_dirty_page()
        self.assertTrue(dirty_page_finshed_flag)

        # 校验备机是否完成数据同步
        logger.info('校验备机是否完成数据同步')
        flag_1 = self.primary_sh.check_data_consistency()
        self.assertTrue(flag_1)
        flag_2 = self.standby_2_sh.check_data_consistency()
        self.assertTrue(flag_2)

    def tearDown(self):
        logger.info('----------------this is tearDown-----------------------')
        logger.info("------------------------recover socket file------------------")
        recover_cmd = f'chmod 700 {self.file_name}'
        logger.info(recover_cmd)
        self.dbPrimaryRootNode.sh(recover_cmd)

        logger.info("---------------------drop database--------------------")
        result = self.primary_sh.executDbSql(f'drop database {self.dbname};')
        logger.info(result)